package com.test;

import junit.framework.TestCase;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * Created by Administrator on 2016/3/14.
 */
public class JMSProducer extends TestCase {

    public void testProducer() throws NamingException {
        Context context = new InitialContext();
        QueueConnectionFactory factory = (QueueConnectionFactory) context.lookup("QueueConnectionFactory");
        QueueConnection connection = null;
        try {
            connection = factory.createQueueConnection();
            connection.start();

            Queue queue = (Queue) context.lookup("MyQueue");
            Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(queue);

            for (int i = 0; i < 10; i++) {
                String message = "message" + i;
                TextMessage textMessage = session.createTextMessage(message);
                System.out.println(message);
                producer.send(textMessage);
            }

            session.commit();
        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            try {
                assert connection != null;
                connection.close();
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }

    }

}
